#include "KTaskProgress.h"

KTaskProgress::KTaskProgress(HWND hWnd, ULONGLONG maxProgress) :
    hWindow(hWnd), taskBarList(NULL), status(TBPF_NOPROGRESS), uCur(0), uMax(maxProgress)
{
    if (isWin7()) {
        CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, __uuidof(ITaskbarList3),
            reinterpret_cast<LPVOID *>(&taskBarList));
    }
}

KTaskProgress::~KTaskProgress()
{
    if (taskBarList) {
        taskBarList->Release();
    }
}

HWND KTaskProgress::attach(HWND hWnd)
{
    HWND prev = hWindow;
    hWindow = hWnd;
    return prev;
}

void KTaskProgress::setStatus(TBPFLAG newStatus)
{
    if (taskBarList) {
        status = newStatus;
        taskBarList->SetProgressState(hWindow, status);
    }
}

void KTaskProgress::setProgress(ULONGLONG newProgress)
{
    if (taskBarList) {
        uCur = newProgress;
        taskBarList->SetProgressValue(hWindow, uCur, uMax);
    }
}

void KTaskProgress::setMaxProgress(ULONGLONG newMax, bool update)
{
    if (taskBarList) {
        uMax = newMax;
        if (update) {
            taskBarList->SetProgressValue(hWindow, uCur, uMax);
        }
    }
}

bool KTaskProgress::isWin7()
{
    OSVERSIONINFO osvi = {sizeof(OSVERSIONINFO)};
    if (GetVersionEx(&osvi)) {
        if (osvi.dwMajorVersion > 6) {
            return true;
        } else if (osvi.dwMajorVersion == 6) {
            return osvi.dwMinorVersion >= 1;
        }
    }
    return false;
}